/*************************************************************************
> File Name: server.c
> Author: High~兵 
> Mail: QQ:1398055460 
> Created Time: 2019年08月03日 星期六 12时03分51秒
************************************************************************/

#include<stdio.h>
#include <sqlite3.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <signal.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>

int main(int argc , char * argv[])
{
    if(argc != 3)
    {
        printf(" eg:  ./xxx   ip  port\n");
        return -1;
    }

    int sockfd = socket(AF_INET,SOCK_STREAM,0);//创建套接字
    if(sockfd < 0)
    {
        perror("sockfd error");
        return -1;
    }
    struct sockaddr_in myaddr;//配置服务器
    myaddr.sin_family = AF_INET;
    myaddr.sin_port = htons(atoi(argv[2]));//port端口
    myaddr.sin_addr.s_addr = inet_addr(argv[1]);//ip地址
    socklen_t len = sizeof(myaddr);
    int ret = bind(sockfd,(struct sockaddr*)&myaddr,len);//绑定地址
    if(ret < 0)
    {
        perror("bind error");
        return -1;
    }
    printf("bind ok !\n");
    char xxx[32][32] = {0};
    int j = 0;
    listen(sockfd,10);
    fd_set readfds = {0};
    fd_set allfds = {0};
    FD_SET(sockfd,&readfds);
    allfds = readfds;
    int maxfd = sockfd;
    struct sockaddr_in clientaddr;//client地址/端口
    sqlite3 * db;
    int ret = sqlite3_open("./test.db",&db);//打开数据库
    if(ret < 0)
    {
        perror("sqlite3_open error");
        return -1;
    }
    char * sql = "select * from word;";

    char ** result ;
    int row = 0, clo = 0;
    char * errmsg;
    ret = sqlite3_get_table(db,sql,&result,&row,&col,&errmsg);
    if(ret < 0)
    {
        perror("sqlite3_get_table error");
        return -1;
    }
    while(1)
    {
        readfds = allfds;
        select (maxfd+1,&readfds,NULL,NULL,NULL);//等待数据流
        for(int i = sockfd;i <= maxfd+1;i++)
        {
            if(FD_ISSET(i,&readfds))//判断fd描述符是否在set集合当
            {
                if(i == sockfd)
                {
                    int confd = accept(sockfd,(struct sockaddr*)&clientaddr,&len);//连接客户端
                    if(confd > maxfd)
                    maxfd = confd;
                    FD_SET(confd,&allfds);//将confd编号的描述符加入到集合当中
                }
                else
                {
                    char buff[1024] = {0};
                    ret = recv(i,buff,sizeof(buff),0);//接收单词
                    printf("%s",buff);
                    for(int i = 0;i <= row;i++)
                    {
                        if(!strcmp(result[i*col + 1]),buff);
                        send(restlt[i*col + 2],strlen(result[i*col +2],)
                    }
                    
                }
            }
        }

    }
return 0;
}

